package com.chinasoft.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 中软zhang
 * @create 2023-08-11 16:33
 */
public class BaseServlet extends HttpServlet {

    /**
     * 根据路径不同调用不同的方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // /brand/selectAll
      // 首先取得路径
        String uri = req.getRequestURI();
        System.out.println(uri);
        // /demo/brand/selectAll

        // 取得 selectAll 字符串
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        System.out.println(methodName);

        // 使用反射方式调用 selectAll 方法
        // 取得类对象
        Class<? extends BaseServlet> clazz = this.getClass();
        System.out.println(clazz);
        try {
            // 取得 类对象的方法对象
            Method method = clazz.getMethod(methodName,
                    HttpServletRequest.class, HttpServletResponse.class);

            // 执行方法
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
